import { ElMessage } from 'element-plus'
import { createRouter, createWebHistory } from 'vue-router'
import store from '@/store/index'
const routes = [
  {
    path: '/',
    name: 'home',
    component: () => import('../views/FrontIndex.vue'),
    redirect: 'index',
    children: [
      { path: 'index', name: 'index', component: () => import('../views/frontindex/FrontHome.vue') },
      { path: 'goodslist', name: 'goodslist', component: () => import('../views/frontindex/FrontGoodsList.vue') },
      { path: 'typelist/:type', name: 'typelist', component: () => import('../views/frontindex/FrontTypeList.vue') },
      { path: 'detail/:id', name: 'detail', component: () => import('../views/frontindex/FrontDetail.vue') },
      { path: 'shopcar', name: 'shopcar', component: () => import('../views/frontindex/ShopCar.vue') },
      { path: 'order', name: 'order', component: () => import('../views/frontindex/OrderList.vue') },
      { path: 'user', name: 'user', component: () => import('../views/frontindex/FrontUser.vue') },
      { path: 'recommend/:rec', name: 'recommend', component: () => import('../views/frontindex/FrontRecommendList.vue') },
    ]
  },
  {
    path: '/authorize',
    name: 'authorize',
    component: () => import('../views/Authorize.vue'),
    children: [
      { path: 'register', name: 'register', component: () => import('../views/authorize/Register.vue') },
      { path: 'login', name: 'login', component: () => import('../views/authorize/Login.vue') },
    ]
  },
  {
    path: '/manage',
    name: 'manage',
    redirect: '/manage/recommend',
    component: () => import('../views/BackupIndex.vue'),
    children: [
      { path: 'recommend', name: 'backuprecommend', component: () => import('../views/backup/BackRecommend.vue') },
      { path: 'order', name: 'backuporder', component: () => import('../views/backup/BackOrder.vue') },
      { path: 'goods', name: 'backupgoods', component: () => import('../views/backup/BackGoods.vue') }
    ]
  },

]


const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})
// 导航守卫 权限检查
router.beforeEach((to, from, next) => {
  let name = [
    'index', 'typelist', 'detail', 'register', 'login', 'goodslist'
  ]
  const flag = store.getters.isLogin;
  console.log(to.name);
  // 访问数组中的路由名时直接放行
  if (name.includes(to.name)) {
    console.log(name.includes(to.name))
    next();
  }
  // 不是以上路由且没登录不放行
  else {
    if (flag) {
      console.log(flag)
      next();
    } else {
      ElMessage({
        message: '请先登录',
        type: 'error'
      })
      next({ name: 'login' });
    }
  }

})

export default router
